<template>
    <div>
        <div class="video-div">
            <div v-show="!imgUrl" class="img_bg_camera">
                <video
                    v-show="showVideo"
                    id="video"
                    ref="video"
                    class="video"
                    webkit-playsinline="true"
                    playsinline="true"
                    autoplay
                    :width="videoWidthAndHeight"
                    :height="videoWidthAndHeight" />
                <canvas id="canvas" ref="canvas" :width="videoWidthAndHeight" :height="videoWidthAndHeight" />
            </div>
            <div v-show="imgUrl" class="img_bg_camera">
                <img :width="videoWidthAndHeight" :height="videoWidthAndHeight" :src="imgUrl">
            </div>
        </div>
        <div class="threemsg-div">
                <!-- <span>正对手机</span>
                <span>光线充足</span>
                <span>脸无遮挡</span> -->
            </div>
    </div>
</template>

<script setup name="useFaceMsg">
import { ref,nextTick } from 'vue'
const videoWidthAndHeight = ref(279)
const imgUrl = ref("")
const canvas = ref()
const video = ref(null)
const showVideo = ref(false)
const ctx = ref()
const  wakeUpTimes = ref(0)
const openCamera = () => { // 打开摄像头
    return new Promise((resolve,reject) => {
        nextTick(() => {
            imgUrl.value = ""
            if (navigator.mediaDevices === undefined) {
                navigator.mediaDevices = {}
            }

            if (navigator.mediaDevices.getUserMedia === undefined) {
                navigator.mediaDevices.getUserMedia = function(constraints) {
                    let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia
                    if (!getUserMedia) {
                        return Promise.reject(new Error("getUserMedia is not implemented in this browser"))
                    }
                    return new Promise(function(resolve, reject) {
                        getUserMedia.call(navigator, constraints, resolve, reject)
                    })
                }
            }
            const constraints = {
                audio: false,
                video: { 
                    width: videoWidthAndHeight.value, 
                    height: videoWidthAndHeight.value,
                    transform: "scaleX(-1)" 
                }
            }
            navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
                if ("srcObject" in video.value) {
                    video.value.srcObject = stream
                } else {
                    video.value.src = window.URL.createObjectURL(stream)
                }
                video.value.onloadedmetadata = function(e) {
                    showVideo.value = true
                    video.value.play()
                }
                resolve(true)
            })
                .catch((error) => {
                    showVideo.value = false
                    console.log("没有开启摄像头权限或浏览器版本不兼容")
                    reject(error)
                    if(wakeUpTimes.value < 1){
                        openCamera()
                        wakeUpTimes.value = wakeUpTimes.value + 1
                    }else{
                        wakeUpTimes.value = 0
                    }
                })
        })
    })
  
}
const stopNavigator = () => {  
    showVideo.value = false
    // 关闭摄像头  
    if (video.value && video.value.srcObject) {  
        // 确保 srcObject 至少有一个 track  
        // 媒体流还没有被设置到视频元素，或者它已经被设置为 null（例如，在另一个地方被清除）。
        if (video.value.srcObject.getTracks().length > 0) {  
            video.value.srcObject.getTracks()[0].stop();  
        } else {  
            console.log("媒体流中没有可用的 track");  
        }  
    } else {  
        console.log("没有开启摄像头权限，摄像头未启动，或浏览器版本不兼容");  
    }  
}
const drawImage = async() => { // 绘制照片
    ctx.value = canvas.value.getContext("2d")
    ctx.value.drawImage(video.value, 0, 0)// 获取图片地址
    let imageData = canvas.value.toDataURL("image/jpeg", 1)
    imgUrl.value = imageData
    let start = imageData.indexOf('base64,') + 7
    let imgbase64 = imageData.substring(start, imageData.length)
    return imgbase64
}// 清空
defineExpose({
    stopNavigator,
    openCamera,
    drawImage
})
</script>

<style lang="less" scoped>
.video-div {
    width: 295px;
    height: 295px;
    margin: 40px auto;
    border-radius: 50%;
    
    border: 5px solid @theme-color;
    padding: 3px;
    overflow: hidden;
    .img_bg_camera {
        border-radius: 139.5px / 139.5px;
        overflow: hidden;
        #video {
            width: 100%;
            height: 100%;
            transform:rotateY(180deg)
        }
        img {
            width: 100%;
            height: 100%;
            transform:rotateY(180deg)
        }
        .video,img {
            border-radius: 139.5px / 139.5px;
        }
    }
}
.threemsg-div {
    content: @face-hint-img;
    width: 70%; 
    // height: 58%;       
    margin: 0 auto;
    margin-top: 12px;
    margin-bottom: 70px;
}

</style>